package com.drd.dt.modular.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.drd.dt.back.dao.GoodsSpecificationBaseMapper;
import com.drd.dt.back.entity.GoodsSpecification;
import com.drd.dt.back.entity.OwnGoods;
import com.drd.dt.common.Constant;
import com.drd.dt.common.SuccessResultEnum;
import com.drd.dt.common.tips.Tip;
import com.drd.dt.exception.BizExceptionEnum;
import com.drd.dt.exception.BussinessException;
import com.drd.dt.modular.dao.OrderGiftMapper;
import com.drd.dt.modular.dao.OwnGoodsMapper;
import com.drd.dt.modular.dao.UserMapper;
import com.drd.dt.modular.dto.OwnGoodsOrderDTO;
import com.drd.dt.modular.dto.PayDTO;
import com.drd.dt.modular.dto.UserInfoDTO;
import com.drd.dt.modular.entity.OrderGift;
import com.drd.dt.modular.entity.User;
import com.drd.dt.modular.service.OwnGoodsService;
import com.drd.dt.modular.service.PayService;
import com.drd.dt.util.JedisClient;
import com.drd.dt.util.ResultUtil;
import com.drd.dt.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Service
@Transactional
public class OwnGoodsServiceImpl implements OwnGoodsService {

    @Autowired
    private JedisClient jedisClient;

    @Autowired
    private OwnGoodsMapper ownGoodsMapper;

    @Autowired
    private PayService payService;

    @Autowired
    private OrderGiftMapper orderGiftMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private GoodsSpecificationBaseMapper mapper;

    @Override
    public Tip getOwnGoodsList(int index, int size) {
        Page page = new Page(index, size);
        List<OwnGoods> all = ownGoodsMapper.getOwnGoodsNoTypeList(page);
        page.setRecords(all);
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), page);
    }

    @Override
    public Tip getOwnGoodsTypeList(int index, int size,int type) {
        Page page = new Page(index, size);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("type",type);
        // 查询商品列表
        List<OwnGoods> all = ownGoodsMapper.getOwnGoodsList(page, map);
        page.setRecords(all);
        //查询数据库分组
        List<Map> typeList =  ownGoodsMapper.groupingType();
        JSONObject obj = new JSONObject();
        obj.put("list",page);
        obj.put("typeList",typeList);
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), obj);
    }


    @Override
    public Tip getOwnGoodsDetails(int dealer_id) {
        //商品详情
        OwnGoods ownGoods = ownGoodsMapper.getOwnGoodsDetails(dealer_id);
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), ownGoods);
    }


    @Override
    public void addOrderGift(OwnGoodsOrderDTO ownGoodsOrderDTO, HttpServletResponse response, HttpServletRequest request) throws Exception {
        int user_id = ownGoodsOrderDTO.getUser_id();
        Float actual_amount = ownGoodsOrderDTO.getActual_amount();
        if (StringUtils.isEmpty(actual_amount) || actual_amount <= 0){//金额为空
            Tip result = ResultUtil.result(BizExceptionEnum.USER_MONEY_ERROR.getCode(), BizExceptionEnum.USER_MONEY_ERROR.getMessage());
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(result));
            response.getWriter().flush();
            response.getWriter().close();
        }
        if (StringUtils.isEmpty(user_id)){//用户id为空
            Tip result = ResultUtil.result(BizExceptionEnum.USER_USERNAME_EMPTY.getCode(), BizExceptionEnum.USER_USERNAME_EMPTY.getMessage());
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(result));
            response.getWriter().flush();
            response.getWriter().close();
        }else {
            User user = userMapper.selectById(user_id);
            if (null == user){//用户不存在
                Tip result = ResultUtil.result(BizExceptionEnum.OT_USER_ERROR.getCode(), BizExceptionEnum.OT_USER_ERROR.getMessage());
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().write(JSON.toJSONString(result));
                response.getWriter().flush();
                response.getWriter().close();
            }
        }
        if (!StringUtil.isMobileNO(ownGoodsOrderDTO.getShipping_phone())) { //手机格式不支持
            Tip result = ResultUtil.result(BizExceptionEnum.USER_PHONE_ERROR.getCode(), BizExceptionEnum.USER_PHONE_ERROR.getMessage());
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(result));
            response.getWriter().flush();
            response.getWriter().close();
        }
        /** 1 生成订单**/
        /** 1.1 生成订单号 规则 ：user_id + 时间+ goods_id **/
        String orderId = "";
        orderId = ownGoodsOrderDTO.getUser_id() + Constant.yyyymmddhhmmss.format(new Date()) + ownGoodsOrderDTO.getGoods_id();

        //1.1.1 提前预判 是否重复炒作
        String redisData =  (String)jedisClient.get("htsq:addOrderGift:" + orderId);
        if(!StringUtils.isEmpty(redisData)){
            return;
        }
        //1.1.2 提前防止用户多次操作 redis 缓存
        jedisClient.setWithExpire("htsq:addOrderGift:" + orderId, orderId, 10);

        ownGoodsOrderDTO.setStatus(0);
        ownGoodsOrderDTO.setOrder_id(orderId);
        /** 1.2 查询商品信息**/
        OwnGoods ownGoods = ownGoodsMapper.getOwnGoodsDetails(ownGoodsOrderDTO.getGoods_id());
        if (null != ownGoods) {
            /** 1.2.1 订单存货验证**/
            Integer number = ownGoodsOrderDTO.getNumber();
            if (null == number) {
                number = 1;
            }
            if (!(ownGoods.getInventory() >= number)) { //库存不够
                throw new BussinessException(BizExceptionEnum.GOODS_NUM_ERROR);
            }
            if (null != ownGoods.getCarousel_imagsList() && ownGoods.getCarousel_imagsList().size() > 0) {
                ownGoodsOrderDTO.setGoods_image(ownGoods.getCarousel_imagsList().get(0));//默认轮播第一张图
            }
            ownGoodsOrderDTO.setGoods_name(ownGoods.getTitle());
        } else {//商品不存在 返回提示
//            return ResultUtil.result(BizExceptionEnum.GOODS_DETAIL_IS_EMPTY.getCode(), BizExceptionEnum.GOODS_DETAIL_IS_EMPTY.getMessage());
        }
        /** 1.3 数据库写入订单**/
        OrderGift gift = orderGiftMapper.getOrderGiftDetail(orderId);
        if (gift != null && gift.getOrder_id().equals(orderId)) {//orderID已经存在，不重复添加
            return;
        }

        int req = orderGiftMapper.addOrderGift(ownGoodsOrderDTO);
        if (req > 0) {
            /** 1.4 如果没有user没有基础地址 保存一个 **/
            UserInfoDTO infoDTO = userMapper.getUserInfo(ownGoodsOrderDTO.getUser_id());
            if (null != infoDTO && StringUtils.isEmpty(infoDTO.getAddr())) {
                User user = new User();
                user.setAddr(ownGoodsOrderDTO.getShipping_address());
                user.setId(ownGoodsOrderDTO.getUser_id());
                userMapper.updateUserAddr(user);
            }
            /** 2 根据actual_amount_type 走不同 付款方式**/
            switch (ownGoodsOrderDTO.getActual_amount_type()) {
                case 1: {
                    PayDTO payDTO = new PayDTO();
                    payDTO.setPaytype(1);
                    payDTO.setMoney(ownGoodsOrderDTO.getActual_amount() + "");
                    payDTO.setTitle(ownGoodsOrderDTO.getGoods_name());
                    payDTO.setOrder_id(ownGoodsOrderDTO.getOrder_id());
                    payDTO.setGoods_id(ownGoodsOrderDTO.getGoods_id() + "");
                    payService.alipayH5(response, request, payDTO);
//                return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), tip);
                }
                break;
                case 2: {
                    PayDTO payDTO = new PayDTO();
                    payDTO.setPaytype(2);
                    payDTO.setMoney(ownGoodsOrderDTO.getActual_amount() * 100 + "");
                    payDTO.setTitle(ownGoodsOrderDTO.getGoods_name());
                    payDTO.setOrder_id(ownGoodsOrderDTO.getOrder_id());
                    payDTO.setGoods_id(ownGoodsOrderDTO.getGoods_id() + "");
                    payService.wxpayH5(response, request, payDTO);
                }
                break;
                default: { //支付方式错误
//                return ResultUtil.result(BizExceptionEnum.PATTERN_OF_PAYMENT_EXCEPTION.getCode(), BizExceptionEnum.PATTERN_OF_PAYMENT_EXCEPTION.getMessage());
                }
            }

        } else {
            throw new BussinessException(BizExceptionEnum.PATTERN_OF_PAYMENT_EXCEPTION);
        }


    }

    @Override
    public Tip getOrderGiftDetail(String order_id) {
        //查询订单详情
        OrderGift ownGoods = orderGiftMapper.userOrderGiftDetail(order_id);
        //规格查询
        List<Long> ids = new ArrayList<>();
        if (null != ownGoods && null != ownGoods.getGoods_spe_id() && ownGoods.getGoods_spe_id().length() > 0) {
            String[] id_s = ownGoods.getGoods_spe_id().split(",");
            for (String s : id_s) {
                ids.add(Long.parseLong(s));
            }
        }
        String spec = "";
        for (GoodsSpecification specification : mapper.getGoodsSpecification(ids)) {
            if (spec.length() > 0) {
                spec = spec + ",";
            }
            spec = spec + specification.getEtalon_value();
        }
        ownGoods.setGetGoods_spe_idText(spec);
        //查询自营商品单位
        OwnGoods ownGoods1 = ownGoodsMapper.getOwnGoodsDetails(Integer.parseInt(ownGoods.getProduct_id()));
        if (null != ownGoods1) {
            ownGoods.setGoods_units(ownGoods1.getGoods_units());
        }
        if (null != ownGoods) {
            if (ownGoods.getProduct_name().length() > 30) {
                ownGoods.setProduct_name(ownGoods.getProduct_name().substring(0, 30) + "...");
            }
            return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), ownGoods);
        }
        return ResultUtil.result(BizExceptionEnum.SELECT_ERROR.getCode(), BizExceptionEnum.SELECT_ERROR.getMessage());
    }

    @Override
    public Tip getGoodsSpecificationDetails(int goods_id) {
        List<GoodsSpecification> all = ownGoodsMapper.getGoodsSpecificationDetails(goods_id);
        Map<String, List<GoodsSpecification>> stringListMap = new HashMap<String, List<GoodsSpecification>>();
        for (GoodsSpecification h : all) {
            List<GoodsSpecification> reqData = null;
            if (stringListMap.containsKey(h.getEtalon_name())) {
                reqData = stringListMap.get(h.getEtalon_name());
            } else {
                reqData = new ArrayList<GoodsSpecification>();
            }
            reqData.add(h);
            stringListMap.put(h.getEtalon_name(), reqData);
        }
        //特殊处理 前端数据结构要求
        List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
        for (String s : stringListMap.keySet()) {
            Map<String, Object> m = new HashMap<String, Object>();
            m.put("info", s);
            List<GoodsSpecification> reqData = stringListMap.get(s);
            m.put("project", reqData);
            dataList.add(m);
        }
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), dataList);
    }
}
